package com.phoenix.jsef.code.generator.template;

import com.phoenix.jsef.code.generator.provider.SchemaProviderFactory;
import com.phoenix.jsef.common.CUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.Map;

@ConfigurationProperties(prefix = "entity-tags-template", ignoreUnknownFields = false)
@PropertySource("classpath:template.properties")
@Component
public class GeneratorEntityTagsTemplate {
	
	@Autowired
	private  SchemaProviderFactory schemaProviderFactory;
	
	@Autowired
	private Configuration config;
	
	private String templateName;
	private String packageName;
	private String imports;
	private String outputFilePath;
	
	
	
	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}

	public String getPackageName() {
		return packageName;
	}

	public void setPackageName(String packageName) {
		this.packageName = packageName;
	}

	public String getImports() {
		return imports;
	}

	public void setImports(String imports) {
		this.imports = imports;
	}

	public String getOutputFilePath() {
		return outputFilePath;
	}

	public void setOutputFilePath(String outputFilePath) {
		this.outputFilePath = outputFilePath;
	}
	
	public void renderToFile(String sourceTable,Map<String, Object> dataModel) throws Exception {
		if(null == dataModel || dataModel.size()<1)//如果未提供数据模型则创建数据模型
			dataModel = schemaProviderFactory.createDbSchemaProvider().prepareDataModel(sourceTable);	
	
		Template template = config.getTemplate(this.getTemplateName());
		
		File file = new File(this.getOutputFilePath()+"\\"+"C"+CUtils.underlineToCamel(sourceTable.toLowerCase(),true)+"Tags"+".java");
	    if (!file.getParentFile().exists()) {  
	        file.getParentFile().mkdirs();   
	    }
		FileWriter fw = new FileWriter(file);

		dataModel.put("imports", Arrays.asList(imports.split(";")));
		dataModel.put("packageName", this.getPackageName());

		template.process(dataModel, fw);
		fw.close();
		dataModel.clear();
	}
	

}
